<template>
  <div class="home">
    <!-- 左侧控制面板 -->
    <div class="left-panel" :class="{ collapsed: !leftPanelExpanded }">
      <!-- 收缩按钮 -->
      <div class="toggle-btn" @click="toggleLeftPanel">
        <i :class="leftPanelExpanded ? 'el-icon-d-arrow-left' : 'el-icon-d-arrow-right'"></i>
      </div>

      <!-- 面板内容 -->
      <div class="panel-content" v-show="leftPanelExpanded">
        <!-- 关系图管理 -->
        <div class="management-section">
          <div class="section-header" @click="toggleSection('chart')">
            <i class="el-icon-s-grid section-icon"></i>
            <span class="section-title">关系图管理</span>
            <i :class="chartSectionExpanded ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" class="expand-icon"></i>
          </div>
          <div class="section-content" v-show="chartSectionExpanded">
            <div class="selector-row">
              <el-select v-model="currentChartId" @change="onChartChange" size="small" style="width: 100%;">
                <el-option
                  v-for="chart in allCharts"
                  :key="chart.id"
                  :label="chart.name + (chart.is_default ? ' (默认)' : '')"
                  :value="chart.id"
                >
                  <span style="float: left">{{ chart.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">
                    {{ chart.node_count }}节点
                  </span>
                </el-option>
              </el-select>
            </div>
            <div class="action-row">
              <el-button size="mini" @click="duplicateCurrentChart">
                <i class="el-icon-copy-document"></i> 复制
              </el-button>
              <el-button size="mini" @click="editCurrentChart">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
            </div>
            <div class="action-row">
              <el-button type="primary" size="mini" @click="showCreateChartDialog">
                <i class="el-icon-plus"></i> 新建图表
              </el-button>
              <el-button type="info" size="mini" @click="showChartsDialog">
                <i class="el-icon-menu"></i> 图表管理
              </el-button>
            </div>
          </div>
        </div>

        <!-- 节点关系管理 -->
        <div class="management-section">
          <div class="section-header" @click="toggleSection('node')">
            <i class="el-icon-connection section-icon"></i>
            <span class="section-title">节点关系管理</span>
            <i :class="nodeSectionExpanded ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" class="expand-icon"></i>
          </div>
          <div class="section-content" v-show="nodeSectionExpanded">
            <div class="action-row">
              <el-button type="primary" size="mini" @click="showAddNodeDialog" style="width: 100%;">
                <i class="el-icon-plus"></i> 添加节点
              </el-button>
            </div>
            <div class="action-row">
              <el-button type="success" size="mini" @click="showAddRelationDialog" style="width: 100%;">
                <i class="el-icon-connection"></i> 添加关系
              </el-button>
            </div>
            <div class="action-row">
              <el-button type="info" size="mini" @click="showManageDialog" style="width: 100%;">
                <i class="el-icon-setting"></i> 数据管理
              </el-button>
            </div>
            <div class="stats-mini">
              <div class="stat-item">
                <span class="stat-label">节点数</span>
                <span class="stat-value">{{ nodeCount }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">关系数</span>
                <span class="stat-value">{{ relationshipCount }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">类型数</span>
                <span class="stat-value">{{ nodeTypes }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 收缩状态的图标 -->
      <div class="collapsed-icons" v-show="!leftPanelExpanded">
        <div class="icon-item" @click="expandAndShowSection('chart')" title="关系图管理">
          <i class="el-icon-s-grid"></i>
        </div>
        <div class="icon-item" @click="expandAndShowSection('node')" title="节点关系管理">
          <i class="el-icon-connection"></i>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content" :class="{ expanded: !leftPanelExpanded }">
      <IndustrialChainChart
        ref="chart"
        :chart-id="currentChartId"
        :chart-name="currentChartName"
        @node-click="handleNodeClick"
        @edge-click="handleEdgeClick"
        @node-double-click="handleNodeDoubleClick"
        @node-right-click="handleNodeRightClick"
        @edit-node="handleEditNodeFromChart"
        @delete-node="handleDeleteNodeFromChart"
        @add-relation-from-node="handleAddRelationFromNode"
        @edit-relation="handleEditRelationFromChart"
        @delete-relation="handleDeleteRelationFromChart"
        @add-node-at-position="handleAddNodeAtPosition"
      />
    </div>

    <!-- 新建图表对话框 -->
    <el-dialog title="新建关系图" :visible.sync="createChartDialogVisible" width="500px">
      <el-form :model="newChart" label-width="80px" :rules="chartRules" ref="chartForm">
        <el-form-item label="图表名称" prop="name" required>
          <el-input v-model="newChart.name" placeholder="请输入图表名称"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="newChart.description" placeholder="请输入图表描述"></el-input>
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch v-model="newChart.is_default"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createChartDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="createChart">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 图表管理对话框 -->
    <el-dialog title="图表管理" :visible.sync="chartsDialogVisible" width="80%">
      <div class="table-header">
        <el-button type="primary" size="small" @click="showCreateChartDialog">
          <i class="el-icon-plus"></i> 新建图表
        </el-button>
        <el-button type="warning" size="small" @click="loadCharts">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
      <el-table :data="allCharts" style="width: 100%" v-loading="chartsLoading">
        <el-table-column prop="id" label="ID" width="60"></el-table-column>
        <el-table-column prop="name" label="名称" min-width="150"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="is_default" label="默认" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.is_default" type="primary" size="mini">默认</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="node_count" label="节点数" width="80"></el-table-column>
        <el-table-column prop="relationship_count" label="关系数" width="80"></el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="150">
          <template slot-scope="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="switchToChart(scope.row)">切换</el-button>
            <el-button type="success" size="mini" @click="duplicateChart(scope.row)">复制</el-button>
            <el-button type="warning" size="mini" @click="editChart(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteChart(scope.row)" :disabled="scope.row.is_default">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 编辑图表对话框 -->
    <el-dialog title="编辑图表" :visible.sync="editChartDialogVisible" width="500px">
      <el-form :model="editingChart" label-width="80px" :rules="chartRules" ref="editChartForm">
        <el-form-item label="图表名称" prop="name" required>
          <el-input v-model="editingChart.name" placeholder="请输入图表名称"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="editingChart.description" placeholder="请输入图表描述"></el-input>
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch v-model="editingChart.is_default"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editChartDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateChart">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 原有的节点和关系管理对话框保持不变 -->
    <!-- ... 这里包含之前的所有节点和关系管理对话框代码 ... -->

    <!-- 添加节点对话框 -->
    <el-dialog title="添加节点" :visible.sync="addNodeDialogVisible" width="500px">
      <el-form :model="newNode" label-width="80px" :rules="nodeRules" ref="nodeForm">
        <el-form-item label="节点名称" prop="name" required>
          <el-input v-model="newNode.name" placeholder="请输入节点名称"></el-input>
        </el-form-item>
        <el-form-item label="节点类型" prop="type">
          <el-select v-model="newNode.type" placeholder="请选择节点类型" style="width: 100%">
            <el-option label="供应商" value="supplier"></el-option>
            <el-option label="制造商" value="manufacturer"></el-option>
            <el-option label="分销商" value="distributor"></el-option>
            <el-option label="零售商" value="retailer"></el-option>
            <el-option label="消费者" value="consumer"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="newNode.description" placeholder="请输入节点描述"></el-input>
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="newNode.color"></el-color-picker>
        </el-form-item>
        <el-form-item label="大小">
          <el-slider v-model="newNode.size" :min="30" :max="100"></el-slider>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addNodeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNode">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加关系对话框 -->
    <el-dialog title="添加关系" :visible.sync="addRelationDialogVisible" width="500px">
      <el-form :model="newRelation" label-width="80px" :rules="relationRules" ref="relationForm">
        <el-form-item label="上游节点" prop="upstream_node_id" required>
          <el-select v-model="newRelation.upstream_node_id" placeholder="请选择上游节点" style="width: 100%">
            <el-option
              v-for="node in allNodes"
              :key="node.id"
              :label="node.name"
              :value="node.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下游节点" prop="downstream_node_id" required>
          <el-select v-model="newRelation.downstream_node_id" placeholder="请选择下游节点" style="width: 100%">
            <el-option
              v-for="node in allNodes"
              :key="node.id"
              :label="node.name"
              :value="node.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关系类型">
          <el-select v-model="newRelation.relationship_type" placeholder="请选择关系类型" style="width: 100%">
            <el-option label="供应关系" value="supply"></el-option>
            <el-option label="分销关系" value="distribute"></el-option>
            <el-option label="零售关系" value="retail"></el-option>
            <el-option label="合作关系" value="partner"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关系标签">
          <el-input v-model="newRelation.label" placeholder="请输入关系标签"></el-input>
        </el-form-item>
        <el-form-item label="关系强度">
          <el-slider v-model="newRelation.strength" :min="0.1" :max="1" :step="0.1" show-stops></el-slider>
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="newRelation.color"></el-color-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRelationDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRelation">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 数据管理对话框 -->
    <el-dialog title="数据管理" :visible.sync="manageDialogVisible" width="80%">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="节点管理" name="nodes">
          <div class="table-header">
            <el-button type="primary" size="small" @click="showAddNodeDialog">
              <i class="el-icon-plus"></i> 添加节点
            </el-button>
            <el-button type="warning" size="small" @click="refreshData">
              <i class="el-icon-refresh"></i> 刷新
            </el-button>
          </div>
          <el-table :data="allNodes" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="ID" width="60"></el-table-column>
            <el-table-column prop="name" label="名称" min-width="120"></el-table-column>
            <el-table-column prop="type" label="类型" width="100">
              <template slot-scope="scope">
                <el-tag :type="getNodeTypeTag(scope.row.type)">{{ getNodeTypeName(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip></el-table-column>
            <el-table-column prop="color" label="颜色" width="80">
              <template slot-scope="scope">
                <div :style="{backgroundColor: scope.row.color, width: '20px', height: '20px', borderRadius: '50%'}"></div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="editNodeInTable(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="deleteNodeInTable(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="关系管理" name="relationships">
          <div class="table-header">
            <el-button type="primary" size="small" @click="showAddRelationDialog">
              <i class="el-icon-plus"></i> 添加关系
            </el-button>
            <el-button type="warning" size="small" @click="refreshData">
              <i class="el-icon-refresh"></i> 刷新
            </el-button>
          </div>
          <el-table :data="allRelations" style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="ID" width="60"></el-table-column>
            <el-table-column label="上游节点" min-width="120">
              <template slot-scope="scope">
                {{ getNodeName(scope.row.upstream_node_id) }}
              </template>
            </el-table-column>
            <el-table-column label="下游节点" min-width="120">
              <template slot-scope="scope">
                {{ getNodeName(scope.row.downstream_node_id) }}
              </template>
            </el-table-column>
            <el-table-column prop="relationship_type" label="关系类型" width="100">
              <template slot-scope="scope">
                <el-tag>{{ getRelationTypeName(scope.row.relationship_type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="label" label="标签" min-width="100"></el-table-column>
            <el-table-column prop="strength" label="强度" width="80"></el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="editRelationInTable(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="deleteRelationInTable(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 编辑节点对话框 -->
    <el-dialog title="编辑节点" :visible.sync="editNodeDialogVisible" width="500px">
      <el-form :model="editingNode" label-width="80px" :rules="nodeRules" ref="editNodeForm">
        <el-form-item label="节点名称" prop="name" required>
          <el-input v-model="editingNode.name" placeholder="请输入节点名称"></el-input>
        </el-form-item>
        <el-form-item label="节点类型" prop="type">
          <el-select v-model="editingNode.type" placeholder="请选择节点类型" style="width: 100%">
            <el-option label="供应商" value="supplier"></el-option>
            <el-option label="制造商" value="manufacturer"></el-option>
            <el-option label="分销商" value="distributor"></el-option>
            <el-option label="零售商" value="retailer"></el-option>
            <el-option label="消费者" value="consumer"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="editingNode.description" placeholder="请输入节点描述"></el-input>
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="editingNode.color"></el-color-picker>
        </el-form-item>
        <el-form-item label="大小">
          <el-slider v-model="editingNode.size" :min="30" :max="100"></el-slider>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editNodeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateNode">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 节点详情对话框 -->
    <el-dialog title="节点详情" :visible.sync="nodeDetailDialogVisible" width="600px">
      <div v-if="selectedNode">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ selectedNode.id }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ selectedNode.name }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ getNodeTypeName(selectedNode.type) }}</el-descriptions-item>
          <el-descriptions-item label="颜色">
            <el-tag :color="selectedNode.color">{{ selectedNode.color }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="大小">{{ selectedNode.size }}</el-descriptions-item>
          <el-descriptions-item label="位置">
            ({{ selectedNode.x }}, {{ selectedNode.y }})
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ selectedNode.description || '无' }}
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px;">
          <el-button type="primary" @click="editNodeFromDetail">编辑节点</el-button>
          <el-button type="danger" @click="deleteNode">删除节点</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import IndustrialChainChart from '@/components/IndustrialChainChart.vue'
import { chainAPI } from '@/api'

export default {
  name: 'Home',
  components: {
    IndustrialChainChart
  },
  data() {
    return {
      // 当前选中的图表
      currentChartId: null,
      currentChartName: '产业链关系图',
      allCharts: [],
      chartsLoading: false,

      nodeCount: 0,
      relationshipCount: 0,
      nodeTypes: 0,
      loading: false,
      activeTab: 'nodes',

      // 左侧面板状态
      leftPanelExpanded: false, // 默认收缩
      chartSectionExpanded: true,
      nodeSectionExpanded: true,

      // 对话框显示状态
      createChartDialogVisible: false,
      chartsDialogVisible: false,
      editChartDialogVisible: false,
      addNodeDialogVisible: false,
      addRelationDialogVisible: false,
      manageDialogVisible: false,
      editNodeDialogVisible: false,
      nodeDetailDialogVisible: false,

      // 数据
      allNodes: [],
      allRelations: [],
      selectedNode: null,

      // 表单数据
      newChart: {
        name: '',
        description: '',
        is_default: false
      },
      editingChart: {},
      newNode: {
        name: '',
        type: 'supplier',
        description: '',
        color: '#409EFF',
        size: 50,
        position_x: 0,
        position_y: 0,
        chart_id: null
      },
      newRelation: {
        upstream_node_id: null,
        downstream_node_id: null,
        relationship_type: 'supply',
        label: '',
        strength: 1.0,
        color: '#67C23A',
        chart_id: null
      },
      editingNode: {},

      // 表单验证规则
      chartRules: {
        name: [
          { required: true, message: '请输入图表名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      },
      nodeRules: {
        name: [
          { required: true, message: '请输入节点名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择节点类型', trigger: 'change' }
        ]
      },
      relationRules: {
        upstream_node_id: [
          { required: true, message: '请选择上游节点', trigger: 'change' }
        ],
        downstream_node_id: [
          { required: true, message: '请选择下游节点', trigger: 'change' }
        ]
      }
    }
  },
  async mounted() {
    // 恢复左侧面板状态
    this.restorePanelState()

    await this.loadCharts()
    await this.loadDefaultChart()
    this.loadStats()
    this.loadAllData()
  },
  methods: {
    // 图表管理方法
    async loadCharts() {
      this.chartsLoading = true
      try {
        const response = await chainAPI.getCharts()
        if (response.code === 200) {
          this.allCharts = response.data
        }
      } catch (error) {
        console.error('Load charts error:', error)
      } finally {
        this.chartsLoading = false
      }
    },

    async loadDefaultChart() {
      // 首先尝试从localStorage获取上次选择的图表
      const lastChartId = localStorage.getItem('lastSelectedChartId')
      if (lastChartId) {
        const chartExists = this.allCharts.find(chart => chart.id == lastChartId)
        if (chartExists) {
          this.currentChartId = parseInt(lastChartId)
          this.currentChartName = chartExists.name
          return
        }
      }

      // 如果没有保存的图表ID或图表不存在，则使用默认图表
      try {
        const response = await chainAPI.getDefaultChart()
        if (response.code === 200) {
          this.currentChartId = response.data.id
          this.currentChartName = response.data.name
        } else if (this.allCharts.length > 0) {
          this.currentChartId = this.allCharts[0].id
          this.currentChartName = this.allCharts[0].name
        }
      } catch (error) {
        console.error('Load default chart error:', error)
        if (this.allCharts.length > 0) {
          this.currentChartId = this.allCharts[0].id
          this.currentChartName = this.allCharts[0].name
        }
      }
    },

    onChartChange(chartId) {
      this.currentChartId = chartId
      // 更新图表名称
      const selectedChart = this.allCharts.find(chart => chart.id == chartId)
      if (selectedChart) {
        this.currentChartName = selectedChart.name
      }
      // 保存选择的图表到localStorage
      localStorage.setItem('lastSelectedChartId', chartId)
      this.refreshData()
    },

    showCreateChartDialog() {
      this.createChartDialogVisible = true
      this.newChart = {
        name: '',
        description: '',
        is_default: false
      }
    },

    async createChart() {
      this.$refs.chartForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await chainAPI.createChart(this.newChart)
            if (response.code === 201) {
              this.$message.success('图表创建成功')
              this.createChartDialogVisible = false
              await this.loadCharts()
              this.currentChartId = response.data.id
              // 保存新创建的图表到localStorage
              localStorage.setItem('lastSelectedChartId', response.data.id)
              this.refreshData()
            } else {
              this.$message.error('创建失败: ' + response.message)
            }
          } catch (error) {
            console.error('Create chart error:', error)
            this.$message.error('网络请求失败')
          }
        }
      })
    },

    showChartsDialog() {
      this.chartsDialogVisible = true
      this.loadCharts()
    },

    switchToChart(chart) {
      this.currentChartId = chart.id
      this.currentChartName = chart.name
      // 保存选择的图表到localStorage
      localStorage.setItem('lastSelectedChartId', chart.id)
      this.chartsDialogVisible = false
      this.refreshData()
      this.$message.success(`已切换到图表: ${chart.name}`)
    },

    async duplicateChart(chart) {
      try {
        const response = await chainAPI.duplicateChart(chart.id)
        if (response.code === 201) {
          this.$message.success('图表复制成功')
          await this.loadCharts()
        } else {
          this.$message.error('复制失败: ' + response.message)
        }
      } catch (error) {
        console.error('Duplicate chart error:', error)
        this.$message.error('网络请求失败')
      }
    },

    duplicateCurrentChart() {
      if (this.currentChartId) {
        const currentChart = this.allCharts.find(c => c.id === this.currentChartId)
        this.duplicateChart(currentChart)
      }
    },

    editChart(chart) {
      this.editingChart = { ...chart }
      this.editChartDialogVisible = true
    },

    editCurrentChart() {
      if (this.currentChartId) {
        const currentChart = this.allCharts.find(c => c.id === this.currentChartId)
        this.editChart(currentChart)
      }
    },

    async updateChart() {
      this.$refs.editChartForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await chainAPI.updateChart(this.editingChart.id, this.editingChart)
            if (response.code === 200) {
              this.$message.success('图表更新成功')
              this.editChartDialogVisible = false
              await this.loadCharts()
            } else {
              this.$message.error('更新失败: ' + response.message)
            }
          } catch (error) {
            console.error('Update chart error:', error)
            this.$message.error('网络请求失败')
          }
        }
      })
    },

    async deleteChart(chart) {
      this.$confirm('确定要删除这个图表吗？这将删除图表中的所有节点和关系。', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await chainAPI.deleteChart(chart.id)
          if (response.code === 200) {
            this.$message.success('图表删除成功')
            await this.loadCharts()
            if (this.currentChartId === chart.id) {
              await this.loadDefaultChart()
              this.refreshData()
            }
          } else {
            this.$message.error('删除失败: ' + response.message)
          }
        } catch (error) {
          console.error('Delete chart error:', error)
          this.$message.error('网络请求失败')
        }
      })
    },

    // 原有方法保持不变，但需要添加chart_id参数
    async loadStats() {
      try {
        const response = await chainAPI.getChainData(this.currentChartId)
        if (response.code === 200) {
          this.nodeCount = response.data.nodes.length
          this.relationshipCount = response.data.edges.length
          this.nodeTypes = [...new Set(response.data.nodes.map(n => n.type))].length
        }
      } catch (error) {
        console.error('Load stats error:', error)
      }
    },

    async loadAllData() {
      this.loading = true
      try {
        const [nodesRes, relationsRes] = await Promise.all([
          chainAPI.getNodes(this.currentChartId),
          chainAPI.getRelationships(this.currentChartId)
        ])

        if (nodesRes.code === 200) {
          this.allNodes = nodesRes.data
        }
        if (relationsRes.code === 200) {
          this.allRelations = relationsRes.data
        }
      } catch (error) {
        console.error('Load all data error:', error)
      } finally {
        this.loading = false
      }
    },

    refreshData() {
      this.loadStats()
      this.loadAllData()
      // 图表组件会通过watch自动刷新，无需手动调用
    },

    showAddNodeDialog() {
      this.addNodeDialogVisible = true
      this.newNode = {
        name: '',
        type: 'supplier',
        description: '',
        color: '#409EFF',
        size: 50,
        position_x: Math.random() * 800,
        position_y: Math.random() * 600,
        chart_id: this.currentChartId
      }
    },

    showAddRelationDialog() {
      this.addRelationDialogVisible = true
      this.newRelation = {
        upstream_node_id: null,
        downstream_node_id: null,
        relationship_type: 'supply',
        label: '',
        strength: 1.0,
        color: '#67C23A',
        chart_id: this.currentChartId
      }
      this.loadAllData()
    },

    showManageDialog() {
      this.manageDialogVisible = true
      this.loadAllData()
    },

    async addNode() {
      this.$refs.nodeForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await chainAPI.createNode(this.newNode)
            if (response.code === 201) {
              this.$message.success('节点添加成功')
              this.addNodeDialogVisible = false
              this.refreshData()
            } else {
              this.$message.error('添加失败: ' + response.message)
            }
          } catch (error) {
            console.error('Add node error:', error)
            this.$message.error('网络请求失败')
          }
        }
      })
    },

    async addRelation() {
      this.$refs.relationForm.validate(async (valid) => {
        if (valid) {
          if (this.newRelation.upstream_node_id === this.newRelation.downstream_node_id) {
            this.$message.warning('上游节点和下游节点不能相同')
            return
          }

          try {
            const response = await chainAPI.createRelationship(this.newRelation)
            if (response.code === 201) {
              this.$message.success('关系添加成功')
              this.addRelationDialogVisible = false
              this.refreshData()
            } else {
              this.$message.error('添加失败: ' + response.message)
            }
          } catch (error) {
            console.error('Add relation error:', error)
            this.$message.error('网络请求失败')
          }
        }
      })
    },

    editNodeInTable(node) {
      this.editingNode = { ...node }
      this.editNodeDialogVisible = true
    },

    editNodeFromDetail() {
      this.editingNode = { ...this.selectedNode }
      this.nodeDetailDialogVisible = false
      this.editNodeDialogVisible = true
    },

    async updateNode() {
      this.$refs.editNodeForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await chainAPI.updateNode(this.editingNode.id, this.editingNode)
            if (response.code === 200) {
              this.$message.success('节点更新成功')
              this.editNodeDialogVisible = false
              this.refreshData()
            } else {
              this.$message.error('更新失败: ' + response.message)
            }
          } catch (error) {
            console.error('Update node error:', error)
            this.$message.error('网络请求失败')
          }
        }
      })
    },

    async deleteNodeInTable(node) {
      this.$confirm('确定要删除这个节点吗？这将同时删除相关的所有关系。', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await chainAPI.deleteNode(node.id)
          if (response.code === 200) {
            this.$message.success('节点删除成功')
            this.refreshData()
          } else {
            this.$message.error('删除失败: ' + response.message)
          }
        } catch (error) {
          console.error('Delete node error:', error)
          this.$message.error('网络请求失败')
        }
      })
    },

    async deleteRelationInTable(relation) {
      this.$confirm('确定要删除这个关系吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await chainAPI.deleteRelationship(relation.id)
          if (response.code === 200) {
            this.$message.success('关系删除成功')
            this.refreshData()
          } else {
            this.$message.error('删除失败: ' + response.message)
          }
        } catch (error) {
          console.error('Delete relation error:', error)
          this.$message.error('网络请求失败')
        }
      })
    },

    handleNodeClick(nodeData) {
      this.selectedNode = nodeData
      this.nodeDetailDialogVisible = true
    },

    handleEdgeClick(edgeData) {
      const upstream = this.getNodeName(edgeData.source)
      const downstream = this.getNodeName(edgeData.target)
      this.$message.info(`关系: ${upstream} → ${downstream}`)
    },

    handleNodeDoubleClick(nodeData) {
      this.editingNode = { ...nodeData }
      this.editNodeDialogVisible = true
    },

    handleNodeRightClick({ node, event }) {
      this.$message.info(`右键点击节点: ${node.name}`)
    },

    async deleteNode() {
      this.$confirm('确定要删除这个节点吗？这将同时删除相关的所有关系。', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await chainAPI.deleteNode(this.selectedNode.id)
          if (response.code === 200) {
            this.$message.success('节点删除成功')
            this.nodeDetailDialogVisible = false
            this.refreshData()
          } else {
            this.$message.error('删除失败: ' + response.message)
          }
        } catch (error) {
          console.error('Delete node error:', error)
          this.$message.error('网络请求失败')
        }
      })
    },

    editRelationInTable(relation) {
      this.$message.info('关系编辑功能开发中...')
    },

    getNodeName(nodeId) {
      const node = this.allNodes.find(n => n.id === nodeId)
      return node ? node.name : '未知节点'
    },

    getNodeTypeName(type) {
      const typeMap = {
        supplier: '供应商',
        manufacturer: '制造商',
        distributor: '分销商',
        retailer: '零售商',
        consumer: '消费者'
      }
      return typeMap[type] || type
    },

    getNodeTypeTag(type) {
      const tagMap = {
        supplier: 'warning',
        manufacturer: 'primary',
        distributor: 'success',
        retailer: 'info',
        consumer: 'danger'
      }
      return tagMap[type] || ''
    },

    getRelationTypeName(type) {
      const typeMap = {
        supply: '供应关系',
        distribute: '分销关系',
        retail: '零售关系',
        partner: '合作关系'
      }
      return typeMap[type] || type
    },

    formatDate(dateString) {
      if (!dateString) return ''
      return new Date(dateString).toLocaleDateString()
    },

    // 图表右键菜单事件处理
    handleEditNodeFromChart(node) {
      this.editingNode = { ...node }
      this.editNodeDialogVisible = true
    },

    handleDeleteNodeFromChart(node) {
      this.$confirm('确定要删除这个节点吗？这将同时删除相关的所有关系。', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await chainAPI.deleteNode(node.id)
          if (response.code === 200) {
            this.$message.success('节点删除成功')
            this.refreshData()
          } else {
            this.$message.error('删除失败: ' + response.message)
          }
        } catch (error) {
          console.error('Delete node error:', error)
          this.$message.error('网络请求失败')
        }
      })
    },

    handleAddRelationFromNode(node) {
      this.addRelationDialogVisible = true
      this.newRelation = {
        upstream_node_id: node.id,
        downstream_node_id: null,
        relationship_type: 'supply',
        label: '',
        strength: 1.0,
        color: '#67C23A',
        chart_id: this.currentChartId
      }
      this.loadAllData()
    },

    handleEditRelationFromChart(relation) {
      this.$message.info('关系编辑功能开发中...')
    },

    handleDeleteRelationFromChart(relation) {
      this.$confirm('确定要删除这个关系吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await chainAPI.deleteRelationship(relation.id)
          if (response.code === 200) {
            this.$message.success('关系删除成功')
            this.refreshData()
          } else {
            this.$message.error('删除失败: ' + response.message)
          }
        } catch (error) {
          console.error('Delete relation error:', error)
          this.$message.error('网络请求失败')
        }
      })
    },

    handleAddNodeAtPosition(position) {
      this.addNodeDialogVisible = true
      this.newNode = {
        name: '',
        type: 'supplier',
        description: '',
        color: '#409EFF',
        size: 50,
        position_x: position.x,
        position_y: position.y,
        chart_id: this.currentChartId
      }
    },

    // 左侧面板控制方法
    toggleLeftPanel() {
      this.leftPanelExpanded = !this.leftPanelExpanded
      // 保存面板状态到localStorage
      localStorage.setItem('leftPanelExpanded', this.leftPanelExpanded)
    },

    toggleSection(section) {
      if (section === 'chart') {
        this.chartSectionExpanded = !this.chartSectionExpanded
      } else if (section === 'node') {
        this.nodeSectionExpanded = !this.nodeSectionExpanded
      }
    },

    expandAndShowSection(section) {
      this.leftPanelExpanded = true
      // 保存面板状态到localStorage
      localStorage.setItem('leftPanelExpanded', this.leftPanelExpanded)
      this.$nextTick(() => {
        if (section === 'chart') {
          this.chartSectionExpanded = true
        } else if (section === 'node') {
          this.nodeSectionExpanded = true
        }
      })
    },

    // 恢复面板状态
    restorePanelState() {
      const savedPanelState = localStorage.getItem('leftPanelExpanded')
      if (savedPanelState !== null) {
        this.leftPanelExpanded = savedPanelState === 'true'
      }
      // 如果没有保存的状态，保持默认值(false - 收缩状态)
    }
  }
}
</script>

<style scoped>
.home {
  height: 100%;
  display: flex;
  flex-direction: row;
}

/* 左侧面板 */
.left-panel {
  width: 300px;
  background-color: #f5f7fa;
  border-right: 1px solid #e6e6e6;
  position: relative;
  transition: width 0.3s ease;
  overflow: hidden;
  z-index: 100;
}

.left-panel.collapsed {
  width: 60px;
}

/* 收缩按钮 */
.toggle-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 30px;
  height: 30px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 110;
  font-size: 16px;
  transition: background-color 0.3s;
}

.toggle-btn:hover {
  background-color: #337ecc;
}

/* 面板内容 */
.panel-content {
  padding: 50px 15px 15px;
  height: 100%;
  overflow-y: auto;
}

/* 管理区块 */
.management-section {
  margin-bottom: 20px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.section-header {
  padding: 12px 15px;
  background-color: #fafafa;
  border-bottom: 1px solid #e6e6e6;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: background-color 0.3s;
}

.section-header:hover {
  background-color: #f0f0f0;
}

.section-icon {
  font-size: 16px;
  color: #409eff;
  margin-right: 8px;
}

.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.expand-icon {
  font-size: 12px;
  color: #666;
  transition: transform 0.3s;
}

.section-content {
  padding: 15px;
}

.selector-row,
.action-row {
  margin-bottom: 12px;
  display: flex;
  gap: 8px;
}

.action-row:last-child {
  margin-bottom: 0;
}

/* 迷你统计 */
.stats-mini {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e6e6e6;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  font-size: 12px;
}

.stat-label {
  color: #666;
}

.stat-value {
  color: #409eff;
  font-weight: bold;
}

/* 收缩状态图标 */
.collapsed-icons {
  padding: 60px 10px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.icon-item {
  width: 40px;
  height: 40px;
  background-color: white;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.icon-item:hover {
  background-color: #409eff;
  color: white;
  transform: translateY(-2px);
}

.icon-item i {
  font-size: 18px;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: white;
  transition: margin-left 0.3s ease;
  overflow: hidden;
}

.main-content.expanded {
  margin-left: 0;
}

.dialog-footer {
  text-align: right;
}

.table-header {
  margin-bottom: 15px;
}

.table-header .el-button {
  margin-right: 10px;
}
</style>